# fingerprint_visualizer.py
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.family'] = ['SimHei']  # 设置中文字体为黑体
# plt.rcParams['font.family'] = ['Microsoft YaHei']  # 设置中文字体为微软雅黑
plt.rcParams['axes.unicode_minus'] = False  # 设置负号支持

class FingerprintVisualizer:
    """刑侦痕迹显影系统：可视化结构'指纹'变化"""

    def compare_fingerprints(self, dna_a, dna_b):
        """双指纹对比可视化：生成差异图谱"""
        plt.figure(figsize=(12, 4))

        # 频率指纹对比
        plt.subplot(131)
        min_len = min(len(dna_a['frequencies']), len(dna_b['frequencies']))
        plt.bar([i - 0.2 for i in range(min_len)], dna_a['frequencies'][:min_len], width=0.4, label='健康')
        plt.bar([i + 0.2 for i in range(min_len)], dna_b['frequencies'][:min_len], width=0.4, alpha=0.5, label='损伤')
        plt.xlabel('频率序号')
        plt.ylabel('频率值 (Hz)')
        plt.title('频率指纹对比')
        plt.legend()

        # 振型对比（MAC值）
        plt.subplot(132)
        mac_values = [self._calc_mac(m1, m2) for m1, m2 in zip(dna_a['modes'], dna_b['modes'])]
        plt.plot(range(len(mac_values)), mac_values, 'ro-')
        plt.xlabel('振型序号')
        plt.ylabel('MAC值')
        plt.title('振型对比 (MAC值)')

        # 敏感性热力图
        plt.subplot(133)
        sensitivity_matrix = self._calc_sensitivity(dna_a, dna_b)
        plt.imshow(sensitivity_matrix, cmap='hot')
        plt.colorbar()
        plt.xlabel('参数序号')
        plt.ylabel('参数序号')
        plt.title('敏感性热力图')

        plt.tight_layout()
        return plt.gcf()

    def _calc_mac(self, mode1, mode2):
        """单模态MAC值计算"""
        mode1 = np.array(mode1)
        mode2 = np.array(mode2)
        return np.abs(mode1.T @ mode2) ** 2 / ((mode1.T @ mode1) * (mode2.T @ mode2))

    def _calc_sensitivity(self, dna_a, dna_b):
        """计算敏感性矩阵，这里简单使用频率和阻尼的差异作为示例"""
        min_freq_len = min(len(dna_a['frequencies']), len(dna_b['frequencies']))
        min_damping_len = min(len(dna_a['damping']), len(dna_b['damping']))
        freq_diff = np.abs(np.array(dna_a['frequencies'][:min_freq_len]) - np.array(dna_b['frequencies'][:min_freq_len]))
        damping_diff = np.abs(np.array(dna_a['damping'][:min_damping_len]) - np.array(dna_b['damping'][:min_damping_len]))
        combined_diff = np.concatenate((freq_diff, damping_diff))
        sensitivity_matrix = np.outer(combined_diff, combined_diff)
        return sensitivity_matrix